import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Badge, Button, Col, Form, Icon, Modal, Row, Upload, Card } from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../search.less';
import moment from 'moment';
import DataSet from '@antv/data-set';

import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/graph';

const FormItem = Form.Item;
const formLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

/* eslint react/no-multi-comp:0 */
@connect(({ fileFingerModel, loading }) => ({
  fileFingerModel,
  loading: loading.models.fileFingerModel,
}))
@Form.create()
class FileFinger extends PureComponent {
  state = {
    fileList: [],
    uploading: false,
    fileName: '',
    fingerContent: '',
    selectedRows: [],
    detailVisible: false,
    gjData: {},
    fileId: '',
    text: {},
  };

  columns = [
    {
      title: '操作人',
      dataIndex: 'userName',
    },
    {
      title: '用户名',
      dataIndex: 'userCode',
    },

    {
      title: '文件名称',
      dataIndex: 'fileName',
    },

    {
      title: '操作类型',
      dataIndex: 'operateType',
    },
    {
      title: '操作内容',
      dataIndex: 'operateContent',
    },
    {
      title: '结果',
      dataIndex: 'status',
      render(val) {
        let text = '--';
        let status = '';
        if (val == 200) {
          status = 'success';
          text = '成功';
        } else if (val == 201) {
          status = 'error';
          text = '失败';
        }
        return <Badge status={status} text={text} />;
      },
    },
    {
      title: '操作时间',
      render: (text, record) => moment(text.createTime).format('YYYY-MM-DD HH:mm'),
    },
  ];

  handleUpload = () => {
    const { dispatch } = this.props;
    const { fileList } = this.state;
    if (fileList && fileList.length > 1) {
      Modal.warning({ title: '一次只能上传一个文件' });
      return;
    }

    let filname = '';
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('file', file);
      filname = file.name;
    });

    this.setState({
      uploading: true,
    });
    dispatch({
      type: 'fileFingerModel/save',
      payload: {
        dataList: [],
        pageNum: 0,
        pageSize: 10,
        totalCount: 0,
      },
    });
    dispatch({
      type: 'fileFingerModel/readFileFinger',
      payload: formData,
      callback: res => {
        if (res.result == 'ok') {
          // res.data = "yang,79"
          this.setState({
            fileList: [],
            uploading: false,
            fileName: filname,
            fingerContent: res.data,
          });
          if (!res.data) {
            Modal.success({ title: '指纹信息为空' });
          } else {
            Modal.success({ title: "指纹信息为: '" + res.data + "'" });
            this.queryLogPageList();
          }
        } else {
          this.setState({
            uploading: false,
          });
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  };

  componentDidMount() {}

  // 分页查询列表
  queryLogPageList(pageSize = 10, pageNum = 0) {
    if (!this.state.fingerContent.split(',')[1]) {
      return;
    }
    const { dispatch } = this.props;
    const values = {
      fileId: this.state.fingerContent.split(',')[1],
      pageSize: pageSize,
      pageNum: pageNum,
      fileName: '',
    };
    dispatch({
      type: 'fileFingerModel/queryList',
      payload: values,
    });
  }

  handleStandardTableChange = (pagination, filters, sorter) => {
    // 分页请求
    this.queryLogPageList(pagination.pageSize, pagination.current - 1);
  };
  detailHandelVisible = (flag, fileId) => {
    this.setState({
      detailVisible: !!flag,
      fileId,
    });
    if (flag) {
      const data = {
        fileId: fileId,
        type: 1,
      };
      this.queryGj(data);
    }
  };

  // 文件轨迹
  queryGj(data) {
    const { dispatch } = this.props;
    const values = {
      fileId: (data && data.fileId) || null,
      type: data && data.type,
    };
    dispatch({
      type: 'fileFingerModel/getGj',
      payload: values,
      callback: res => {
        if (res.result == 'ok') {
          this.setState({
            gjData: res.data,
          });
        } else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
  }

  render() {
    const {
      fileFingerModel: { data },
      loading,
    } = this.props;
    const {
      uploading,
      fileList,
      fingerContent,
      fileName,
      selectedRows,
      detailVisible,
      gjData,
      text,
    } = this.state;
    let title = '上传文件';
    let accepts = '.docx,.pdf,.xlsx';
    const detailsMethods = {
      detailHandelVisible: this.detailHandelVisible,
    };

    let fingerparams;
    let fingerId = '';
    let fingerUsercode = '';
    if (fingerContent) {
      fingerparams = fingerContent.split(',');
      fingerId = fingerparams[1];
      fingerUsercode = fingerparams[0];
    }

    const props = {
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        //限制4个G
        const fileMaxUploadSize = 4096;
        const isLt2M = file.size / 1024 / 1024 < fileMaxUploadSize;
        if (!isLt2M) {
          Modal.warning({ title: '上传文件大小超过限制' });
          return false;
        }

        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
      accept: accepts,
      multiple: true,
      // enctype:"multipart/form-data",
    };
    return (
      <PageHeaderWrapper title="文件指纹">
        <Card bordered={false}>
          <Upload {...props}>
            <Button disabled={uploading}>
              <Icon type="upload" /> 选择文件
            </Button>
          </Upload>
          <Button
            type="primary"
            onClick={this.handleUpload}
            disabled={fileList.length === 0}
            loading={uploading}
            style={{ marginTop: 16, float: 'right' }}
          >
            {uploading ? '上传中' : '开始上传'}
          </Button>
          <p
            style={{
              clear: 'both',
              marginTop: '10px',
              lineHeight: 2,
              wordWwrap: 'break-word',
              wordBreak: 'break-all',
            }}
          >
            <span style={{ color: '#ff6c00' }}>提示</span>
            <br />
            1. 目前仅支持docx,xlsx,pdf的指纹提取。
            <br />
            2. 查询结果请及时保存，关闭页面后需重新上传文件查询。
            <br />
            <span style={{ color: '#ff6c00' }}>查询结果</span>
            <br />
            1. 您本次上传的文件： {fileName}
            <br />
            {/* 2. <a onClick={() => this.detailHandelVisible(true, fingerId)}>查看轨迹</a><br/> */}
            2. 查询结果：
            {fingerContent == '' ? '' : `用户编码-${fingerUsercode}；文件id-${fingerId}`}
            <br />
          </p>
          {detailVisible ? (
            <Details
              {...detailsMethods}
              detailVisible={detailVisible}
              gjData={gjData}
              text={text}
            />
          ) : null}

          {fingerContent == '' ? (
            ''
          ) : (
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              hideRowSelection={true}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.id}
            />
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }
}

class Details extends PureComponent {
  componentDidMount() {
    let that = this;
    //
    setTimeout(function() {
      const { gjData } = that.props;
      let categories = ['外发', '流转', '共享', '下载', '上传', '预览'];

      let optionsP = {
        title: {
          text: 'Les Miserables',
          subtext: 'Default layout',
          top: 'bottom',
          left: 'right',
        },
        tooltip: {},
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        label: {
          normal: {
            show: true,
            textStyle: {
              fontSize: 12,
            },
          },
        },
        legend: {
          x: 'center',
          show: true,
          data: categories,
        },
        series: [
          {
            type: 'graph',
            layout: 'force',
            symbolSize: 45,
            focusNodeAdjacency: true,
            roam: true,
            categories: categories,
            label: {
              normal: {
                show: true,
                textStyle: {
                  fontSize: 12,
                },
              },
            },
            force: {
              repulsion: 1000,
            },
            edgeSymbolSize: [4, 50],
            edgeLabel: {
              normal: {
                show: true,
                textStyle: {
                  fontSize: 10,
                },
                formatter: '{c}',
              },
            },
            data: [],
            links: [],
            lineStyle: {
              normal: {
                opacity: 0.9,
                width: 1,
                curveness: 0,
              },
            },
          },
        ],
      };
      if (gjData && gjData.data) {
        optionsP.series[0].data = gjData.data;
        optionsP.series[0].links = gjData.links;
      }
      let myChart = echarts.init(document.getElementById('main'));
      myChart.setOption(optionsP);
      //一些事件
      myChart.on('click', params => {
        console.log(params);
      });
    }, 500);
  }

  render() {
    const { detailVisible, detailHandelVisible, gjData, text } = this.props;
    let data = gjData;
    var dv = new DataSet.View().source(data, {
      type: 'hierarchy',
      pureData: true,
    });
    dv.transform({
      type: 'hierarchy.compact-box',
      direction: 'TB',

      getHGap() {
        return 28;
      },

      getVGap() {
        return 28;
      },

      getHeight() {
        return 28;
      },

      getWidth(d) {
        return 28 * (d && d.userName && d.userName.length);
      },
    });
    return (
      <Modal
        destroyOnClose
        width={1200}
        title="查看轨迹"
        visible={detailVisible}
        onOk={() => detailHandelVisible()}
        onCancel={() => detailHandelVisible()}
        footer={[
          <Button key="back" type="primary" onClick={() => detailHandelVisible()}>
            返回
          </Button>,
        ]}
        className={styles.viewMore}
      >
        <div>
          <Row style={{ borderBottom: '1px solid #e8e8e8' }}>
            <Col md={12}>
              <FormItem {...formLayout} label="文件名称">
                {text.fileName}
              </FormItem>
            </Col>

            <Col md={12}>
              <FormItem {...formLayout} label="大小">
                {text.fileSize ? getReadableSize(text.fileSize * 1024) : '--'}
              </FormItem>
            </Col>
            <Col md={12}>
              <FormItem {...formLayout} label="密级">
                {text.secretLevelName}
              </FormItem>
            </Col>
            <Col md={12}>
              <FormItem {...formLayout} label="初始来源">
                {text.fileSourceName}
              </FormItem>
            </Col>
          </Row>
          <div id="main" style={{ height: '500px' }}></div>
        </div>
      </Modal>
    );
  }
}

export default FileFinger;
